<template>
    <div class="theme-content">
        <div class="theme-content-item padding-20px configRuleStyle">
            <div style="height:calc(100% - 62px);overflow-y: scroll;">
                <div class="flex-jc-s-b" style="align-items: center;">
                    <div class="left-title">配置抽题规则</div>
                </div>
                <el-form :rules='rules' :inline="true" ref="ruleFormRef" :model="configRuleRequest"
                    class="demo-form-inline margin-t-b-20px">
                    <el-form-item label="所属类别" class="" prop="courseIdMain">
                        <el-select :disabled="queryReceive.type != 'add'"
                            @change="initCourseOtherOption(), configRuleRequestClear('courseBankTypeId'), configRuleRequestClear('courseParentId'), clearAllQuestion()"
                            v-model="configRuleRequest.courseIdMain" placeholder="请选择类目">
                            <el-option v-for="item, index in saveOptions.courseOption" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <!-- style="margin-left: 0px;" -->
                    <el-form-item label="" prop="courseParentId">
                        <el-select
                            @click.native="saveOptions.courseOtherOption.length == 0 ? ElMessage.warning('请优先选择类目/该类目没有类别') : ''"
                            @change="initCourseBankTypeOption(), clearAllQuestion()"
                            v-model="configRuleRequest.courseParentId" placeholder="请选择类别"
                            :disabled="saveOptions.courseOtherOption.length == 0 || queryReceive.type != 'add'">
                            <el-option v-for="item, index in saveOptions.courseOtherOption" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="题库类型" prop="courseBankTypeId">
                        <el-select v-model="configRuleRequest.courseBankTypeId"
                            @click.native="saveOptions.courseBankTypeOption.length == 0 ? ElMessage.warning('请优先选择类别') : ''"
                            placeholder="请选择题库类型" @change="checkRules('courseBankTypeIdCheckRules')"
                            :disabled="saveOptions.courseBankTypeOption.length == 0 || queryReceive.type != 'add'">
                            <el-option v-for="item, index in saveOptions.courseBankTypeOption" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item>
                    <el-button type="primary" @click="onSubmit">Query</el-button>
                        </el-form-item> -->
                </el-form>
                <div class="flex-jc-s-b" style="align-items: center;">
                    <div class="left-title">练习题库规则
                        <span class="primary-color catBank" v-show="queryReceive.type == 'look'" @click="preview">
                            <svg-icon class-name="search-icon" icon-class="search" @click.stop="click"
                                style="margin-left: 1em;" />
                            预览题库
                        </span>
                    </div>
                    <div class="dotted-primary" style="width: 86%;"></div>
                </div>
                <div class="padding-20px">
                    <div><span>指定类型：</span>
                        <span>
                            <el-radio-group :disabled="queryReceive.type == 'look'"
                                v-model="configRuleRequest.practiceConfModeTypeCode" class="ml-4">
                                <el-radio label="unify" size="large">统一指定</el-radio>
                                <el-radio label="difference" size="large">科目指定</el-radio>
                            </el-radio-group>
                        </span>
                    </div>
                    <div v-show="showPracticeDetail">
                        <div v-for="sub, subIndex in practiceSubOption" style="margin-bottom: 10px;">
                            <div class="flex-jc-start"
                                v-if="configRuleRequest.practiceConfModeTypeCode == 'difference' && sub.name">
                                <div class="flex-jc-start" style="cursor: pointer;"
                                    @click="sub.showPracticeDifference = !sub.showPracticeDifference">
                                    <div class="primary-color">科目{{ subIndex + 1 }}：{{ sub.children.courseName }}</div>
                                    <el-icon><arrow-up class="primary-color"
                                            :style="sub.showPracticeDifference ? '' : 'transform: rotateX(180deg);'" /></el-icon>
                                </div>
                            </div>
                            <div
                                v-show="sub.showPracticeDifference || configRuleRequest.practiceConfModeTypeCode == 'unify'">
                                <div>
                                    <span>练习题库组成：</span><span>抽取全题库的
                                        <el-input :disabled="queryReceive.type == 'look'"
                                            @input="sub.children.practicePercent = IntegerOneHundred(sub.children.practicePercent)"
                                            v-model="sub.children.practicePercent" style="width:50px" />%
                                    </span>
                                </div>
                                <div class="margin-t-10px" style="display:inline-flex;align-items:center">
                                    <span style="line-height: 15px;height: 19px;">题库模式：</span>
                                    <span style="">
                                        <el-checkbox-group :disabled="queryReceive.type == 'look'"
                                            v-model="sub.children.practiceModeCodeList">
                                            <el-checkbox :label="'answer'">答题模式</el-checkbox>
                                            <el-checkbox :label="'recitation'">背题模式</el-checkbox>
                                        </el-checkbox-group>
                                    </span>
                                </div>
                                <!-- 排序 -->
                                <div class="margin-t-10px" style="display:flex;">
                                    <span style="line-height: 15px;height: 19px;">题型排序:</span>
                                    <div style="transform: translateY(-11px);margin:0 17px 0 15px;">
                                        <el-radio-group :disabled="queryReceive.type == 'look'"
                                            v-model="sub.children.practiceOrderRule.typeCode">
                                            <el-radio label="manualSortType" size="large">手动排序</el-radio>
                                        </el-radio-group>
                                    </div>
                                    <div>
                                        <Drag :dargList="dargList.practice[subIndex]"
                                            @arrayChange="arrayChangePractice($event, subIndex)"
                                            :disabled="queryReceive.type == 'look' ? true : false"></Drag>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!--  -->
                </div>
                <div class="flex-jc-s-b" style="align-items: center;">
                    <div class="left-title">模拟考试规则</div>
                    <div class="dotted-primary" style="width:86%"></div>
                </div>
                <div class="padding-20px">
                    <div><span>指定类型：</span>
                        <span>
                            <el-radio-group :disabled="queryReceive.type == 'look'"
                                v-model="configRuleRequest.testConfModeTypeCode" class="ml-4">
                                <el-radio label="unify" size="large">统一指定</el-radio>
                                <el-radio label="difference" size="large">科目指定</el-radio>
                            </el-radio-group>
                        </span>
                    </div>
                    <!--  -->
                    <div v-show="showTestDetail">
                        <div class="left-title" style="margin-bottom: 10px;">模拟考试试卷配置</div>
                        <div v-for="sub, subIndex in testSubOption" style="margin-bottom: 10px;">
                            <div class="flex-jc-start"
                                v-if="configRuleRequest.testConfModeTypeCode == 'difference' && sub.name">
                                <div class="flex-jc-start" style="cursor: pointer;"
                                    @click="sub.showTestFifference = !sub.showTestFifference">
                                    <div class="primary-color">科目{{ subIndex + 1 }}：{{ sub.children.courseName }}</div>
                                    <el-icon><arrow-up class="primary-color"
                                            :style="sub.showTestFifference ? '' : 'transform: rotateX(180deg);'" /></el-icon>
                                </div>
                            </div>
                            <div v-show="sub.showTestFifference || configRuleRequest.testConfModeTypeCode == 'unify'">
                                <!--  -->

                                <div>
                                    <div class="margin-t-b-20px">
                                        <span style="margin-right: 100px;">单选题</span>
                                        <span>抽取<el-input :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testAmountConfMap.single = IntegerOneHundred(sub.children.testAmountConfMap.single, 999)"
                                                v-model="sub.children.testAmountConfMap.single"
                                                style=" width: 88px " />道试题</span>
                                        <span class="margin-l-20px"> 每题<el-input :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testCorrectConfMap.single.mark = IntegerPoint(sub.children.testCorrectConfMap.single.mark, 999.9)"
                                                v-model="sub.children.testCorrectConfMap.single.mark"
                                                style="width:88px" />分</span>
                                    </div>
                                    <div class="margin-t-b-20px">
                                        <span style="margin-right: 100px;">多选题</span>
                                        <span>抽取<el-input :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testAmountConfMap.multiple = IntegerOneHundred(sub.children.testAmountConfMap.multiple, 999)"
                                                v-model="sub.children.testAmountConfMap.multiple"
                                                style=" width: 88px " />道试题</span>
                                        <span class="margin-l-20px"> 每题<el-input :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testCorrectConfMap.multiple.mark = IntegerPoint(sub.children.testCorrectConfMap.multiple.mark, 999.9)"
                                                v-model="sub.children.testCorrectConfMap.multiple.mark"
                                                style="width:88px" />分</span>
                                        <span style="padding-left: 10px;height:19px;line-height: 15px;">
                                            <el-checkbox :disabled="queryReceive.type == 'look'"
                                                v-model="sub.children.testCorrectConfMap.multiple.incompleteHalfMarkFlag">
                                                漏选得一半分</el-checkbox>
                                        </span>
                                    </div>
                                    <div class="margin-t-b-20px">
                                        <span style="margin-right: 100px;">判断题</span>
                                        <span>抽取<el-input v-model="sub.children.testAmountConfMap.judge"
                                                :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testAmountConfMap.judge = IntegerOneHundred(sub.children.testAmountConfMap.judge, 999)"
                                                style=" width: 88px " />道试题</span>
                                        <span class="margin-l-20px"> 每题<el-input :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testCorrectConfMap.judge.mark = IntegerPoint(sub.children.testCorrectConfMap.judge.mark, 999.9)"
                                                v-model="sub.children.testCorrectConfMap.judge.mark"
                                                style="width:88px" />分</span>
                                    </div>
                                    <div class="margin-t-b-20px">
                                        <span style="margin-right: 100px;">案例题</span>
                                        <span>抽取<el-input :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testAmountConfMap.case = IntegerOneHundred(sub.children.testAmountConfMap.case, 999)"
                                                v-model="sub.children.testAmountConfMap.case"
                                                style=" width: 88px " />组试题</span>
                                        <!-- <span class="margin-l-10px">,共0道试题</span> -->
                                        <span class="margin-l-15px">
                                            <span class="margin-l-10px">案例题分数同上</span>
                                        </span>
                                    </div>
                                    <!-- 填空简答 -->
                                    <div class="margin-t-b-20px" v-if="sub.children.testCorrectConfMap.fillBlank">
                                        <span style="margin-right: 100px;">填空题</span>
                                        <span>抽取<el-input v-model="sub.children.testAmountConfMap.fillBlank"
                                                :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testAmountConfMap.fillBlank = IntegerOneHundred(sub.children.testAmountConfMap.fillBlank, 999)"
                                                style=" width: 88px " />道试题</span>
                                        <span class="margin-l-20px"> 每题<el-input :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testCorrectConfMap.fillBlank.mark = IntegerPoint(sub.children.testCorrectConfMap.fillBlank.mark, 999.9)"
                                                v-model="sub.children.testCorrectConfMap.fillBlank.mark"
                                                style="width:88px" />分</span>
                                    </div>
                                    <div class="margin-t-b-20px" v-if="sub.children.testCorrectConfMap.shortAnswer">
                                        <span style="margin-right: 100px;">简答题</span>
                                        <span>抽取<el-input v-model="sub.children.testAmountConfMap.shortAnswer"
                                                :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testAmountConfMap.shortAnswer = IntegerOneHundred(sub.children.testAmountConfMap.shortAnswer, 999)"
                                                style=" width: 88px " />道试题</span>
                                        <span class="margin-l-20px"> 每题<el-input :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testCorrectConfMap.shortAnswer.mark = IntegerPoint(sub.children.testCorrectConfMap.shortAnswer.mark, 999.9)"
                                                v-model="sub.children.testCorrectConfMap.shortAnswer.mark"
                                                style="width:88px" />分</span>
                                    </div>
                                </div>
                                <div class="margin-t-b-20px"><span>测试用时：</span><span>
                                        <el-input :disabled="queryReceive.type == 'look'"
                                            v-model="sub.children.testDurationMinute"
                                            @input="sub.children.testDurationMinute = IntegerOneHundred(sub.children.testDurationMinute, 999)"
                                            style="width:150px" />分钟</span>
                                </div>
                                <!-- 排序 -->
                                <div class="margin-t-10px" style="display:flex;">
                                    <span style="line-height: 15px;height: 19px;">题型排序</span>
                                    <div style="transform: translateY(-11px);">
                                        <el-radio-group class="flex-column" style="justify-content: flex-start;"
                                            :disabled="queryReceive.type == 'look'"
                                            v-model="sub.children.testOrderRule.typeCode">
                                            <el-radio label="manualSortType" style="transform: translateX(16px);"
                                                size="large">手动排序</el-radio>
                                            <el-radio label="disruption" size="large">顺序打乱</el-radio>
                                        </el-radio-group>
                                    </div>
                                    <div>
                                        <Drag :dargList="dargList.test[subIndex]"
                                            @arrayChange="arrayChangeTest($event, subIndex)"
                                            :disabled="queryReceive.type == 'look' ? true : false"></Drag>
                                    </div>
                                </div>
                                <div>
                                    <span>题目来源：</span>
                                    <span>
                                        <span>试卷题目</span>
                                        <el-input :disabled="queryReceive.type == 'look'"
                                            @input="sub.children.testPracticePercent = linkPractice(sub, 'testPracticePercent', 'testResiduePercent')"
                                            v-model="sub.children.testPracticePercent" style="width:50px" />%来源于练习题库
                                        <br />
                                        <div style="margin-top: 20px; margin-left: 5em;">
                                            <span>试卷题目</span>
                                            <el-input :disabled="queryReceive.type == 'look'"
                                                @input="sub.children.testResiduePercent = linkPractice(sub, 'testResiduePercent', 'testPracticePercent')"
                                                v-model="sub.children.testResiduePercent" style="width:50px" />%来源于全题库剩余题目
                                        </div>
                                    </span>
                                </div>
                            </div>
                            <!-- <div v-if="configRuleRequest.testConfModeTypeCode != 'difference'" class="primary-color margin-b-20px">
                        共抽取{{ configRuleRequest.testTotalAmount }}题，
                                                                        共{{ configRuleRequest.testTotalMark }}分</div> -->
                        </div>
                    </div>
                </div>
            </div>
            <div class="saveConfig">
                <div style="width:151px;margin:auto;" class="flex-jc-s-b">
                    <el-button style="margin-right:0px;" type="default" size="" @click="router.go(-1)">返 回</el-button>
                    <el-button style="margin-left:0px;" v-if="queryReceive.type != 'look'" type="primary" size=""
                        @click="saveConfig">保 存</el-button>
                </div>
            </div>
        </div>
    </div>
    <!-- 保存失败，展示失败原因 -->
    <el-dialog title="保存失败" v-model="showErrorReason" width="540px">
        <el-tabs v-model="selectedTabName">
            <el-tab-pane v-for="(errorReason, index) in errorReasonList" :label="errorReason.bank.courseName"
                :name="errorReason.bank.courseName">
                <el-table :data="errorReason.message"
                    :header-cell-style="{ 'text-align': 'center', 'background': '#fff', 'height': '44px' }"
                    :cell-style="{ 'text-align': 'center', 'height': '44px' }" style="max-height:440px;overflow-y:scroll">
                    <el-table-column type="index" label="序号" width="200px"></el-table-column>
                    <el-table-column prop="message" label="失败原因"></el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="showErrorReason = false">
                    确 定</el-button>
            </span>
        </template>
    </el-dialog>
    <bankPreview :previewObj="previewObj"></bankPreview>
</template>
<script setup>
import { tableItem, configListApi, configBankApi, ruleAddApi, ruleDetailApi, ruleByParentAndBankTypeApi } from './const.js'
import bankPreview from "../component/bankPreview";
import getPreviewObj from "../hook/useBankPreview.js";
import { onMounted, watch, toRaw, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { IntegerOneHundred, IntegerPoint } from '@/utils/checkInput'
import Drag from '@/views/common/component/drag'
import getConfigRuleObj from './configRule.js'
const previewObj = getPreviewObj()
const configRuleObj = getConfigRuleObj()
const router = useRouter()
const route = useRoute()
const showPracticeDetail = ref(true)
const showTestDetail = ref(true)
const ruleFormRef = ref('')
const dargList = configRuleObj.dargList
const rules = configRuleObj.rules
const saveOptions = configRuleObj.saveOptions
const configRuleRequest = configRuleObj.configRuleRequest
const queryReceive = route.query
const showErrorReason = ref(false);
const errorReasonList = ref([])
const selectedTabName = ref('')

function linkPractice(sub, nowPercent, another) {
    let result = IntegerOneHundred(sub.children[nowPercent])
    if (result == NaN || result == '') {
        return ''
    }
    if (result >= 0 && result <= 100) {
        sub.children[another] = 100 - parseInt(result)

    } else {
        result = 100 - parseInt(sub.children[another])
    }
    return result
}
let practiceSubOption = computed(() => {
    checkRules()
    return configRuleRequest.practiceConfModeTypeCode == 'difference' ? saveOptions.subOption : configRuleObj.subOptionClearSubOption
});
let testSubOption = computed(() => {
    checkRules()
    return configRuleRequest.testConfModeTypeCode == 'difference' ? saveOptions.subOption : configRuleObj.subOptionClearSubOption
});

onMounted(() => {
    initCourseOption()
    // subOptionClear()
    // 查看编辑初始化
    if (!queryReceive.id) { return }
    initConfigRuleRequest()
})
// 测试题库排序回调
const arrayChangeTest = (arr, index) => {
    if (testSubOption.value[index]) {
        testSubOption.value[index].children.testOrderRule.questionTypeCodeList = arr
    }
}
// 练习题库排序回调
const arrayChangePractice = (arr, index) => {
    if (practiceSubOption.value[index]) {
        practiceSubOption.value[index].children.practiceOrderRule.questionTypeCodeList = arr
    }
}
// 修改查看初始化数据
const initConfigRuleRequest = () => {
    ruleDetailApi(queryReceive.id).then((res) => {
        initSaveConfigRule(res)
    })
}
// 初始化参数和显示
const initSaveConfigRule = (res) => {
    if (!res) { return }
    for (const key in configRuleRequest) {
        if (key != 'practiceOrderRule' && key != 'practiceModeCodeList') { configRuleRequest[key] = res.data[key] }
        res.data['practiceOrderRule'] ? configRuleRequest[key] = res.data[key] : ''
        res.data['practiceModeCodeList'] ? configRuleRequest[key] = res.data[key] : ''
        // 
    }
    configRuleRequest.courseIdMain = res.data.courseRootId
    configRuleRequest.id = res.data.id
    // 初始化类别和题目
    initCourseOtherOption() // 非新增的初始化
    //统一指定排序 排序初始化
    // if (!configRuleRequest.practiceOrderRule.questionTypeCodeList) { return }

    if (configRuleRequest.testConfModeTypeCode != 'unify' || configRuleRequest.practiceConfModeTypeCode != 'unify') {
        // saveOptionsChildrenInit(saveOptions.subOption);
        // saveOptionsChildrenInit(configRuleObj.subOptionClearSubOption);
        return
    }

    if (configRuleRequest.id) {
        for (const sub in configRuleRequest) {
            saveOptions.subOption[0].children[sub] = configRuleRequest[sub]
            configRuleObj.subOptionClearSubOption[0].children[sub] = configRuleRequest[sub]
        }
        //统一指定排序 测试题库排序
        dargList.test[0] = []
        configRuleRequest.testOrderRule.questionTypeCodeList.map((item, index) => {
            let saveLabel = ''
            switch (item) {
                case 'single': saveLabel = '单选'
                    break;
                case 'multiple': saveLabel = '多选'
                    break;
                case 'judge': saveLabel = '判断'
                    break;
                case 'case': saveLabel = '案例'
                    break;
                case 'fillBlank': saveLabel = '填空题'
                    break;
                case 'shortAnswer': saveLabel = '简答题'
                    break;
                default: ''
            }
            dargList.test[0].push({
                label: saveLabel,
                value: item
            })
        })
        dargList.practice[0] = []
        dargList.practice[0] = configRuleRequest.practiceOrderRule.questionTypeCodeList.map((item, index) => {
            let saveLabel = ''
            switch (item) {
                case 'single': saveLabel = '单选'
                    break;
                case 'multiple': saveLabel = '多选'
                    break;
                case 'judge': saveLabel = '判断'
                    break;
                case 'case': saveLabel = '案例'
                    break;
                case 'fillBlank': saveLabel = '填空题'
                    break;
                case 'shortAnswer': saveLabel = '简答题'
                    break;
                default: ''
            }
            return {
                label: saveLabel,
                value: item
            }
        })
    }
}
// 保存检查
const configRequestCheck = (type) => {
    if (!configRuleRequest.practicePercent) { ElMessage.warning('请选择输入练习题库百分比'); return false }
    if (!configRuleRequest.practiceModeCodeList || configRuleRequest.practiceModeCodeList.length == 0) { ElMessage.warning('请选择题库模式'); return false }
    //   统一规则处理
    if (type == 'unify') {
        if (!configRuleRequest.testPracticePercent) { ElMessage.warning('请选择输入模拟考试中占练习题库'); return false }
        if (!configRuleRequest.testResiduePercent) { ElMessage.warning('请输入模拟考试中全题库剩余题库百分比'); return false }
        if (!configRuleRequest.testDurationMinute) { ElMessage.warning('请选择输入测试用时'); return false }
        let totalTestAmountConfMap = 0
        if (configRuleRequest.testAmountConfMap) {
            for (const key in configRuleRequest.testAmountConfMap) {
                configRuleRequest.testAmountConfMap[key] ? totalTestAmountConfMap += configRuleRequest.testAmountConfMap[key] : ''
            }
        }
        if (totalTestAmountConfMap == 0) { ElMessage.warning('请选择输入模拟考试试卷配置'); return false }
        return true
    }
    if (type == 'difference') {
        return true
    }
}
// 保存
const saveConfig = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid, fields) => {
        if (!valid) { return }
        //  科目指定
        if (saveOptions.subOption.length > 0) {
            configRuleRequest.children = []
            saveOptions.subOption.map((item) => {
                configRuleRequest.children.push({ ...item.children })
            })
            configRuleRequest.testOrderRule = null
        }
        {
            // 统一指定
            const { testPracticePercent, testResiduePercent, testDurationMinute, testAmountConfMap
                , testCorrectConfMap, testOrderRule, practicePercent, practiceModeCodeList, practiceOrderRule
            } = configRuleObj.subOptionClearSubOption[0].children
            for (const key in testAmountConfMap) {
                testAmountConfMap[key] ? '' : testAmountConfMap[key] = 0
                if (key != 'case') {
                    testCorrectConfMap[key].mark ? '' : testCorrectConfMap[key].mark = 0
                }
            }
            configRuleRequest.practicePercent = practicePercent || 0
            configRuleRequest.practiceModeCodeList = practiceModeCodeList
            configRuleRequest.practiceOrderRule = practiceOrderRule
            configRuleRequest.testPracticePercent = testPracticePercent || 0
            configRuleRequest.testResiduePercent = testResiduePercent || 0
            configRuleRequest.testDurationMinute = testDurationMinute
            configRuleRequest.testAmountConfMap = testAmountConfMap
            configRuleRequest.testCorrectConfMap = testCorrectConfMap
            configRuleRequest.testOrderRule = testOrderRule
        }
        // 测试题检测
        if (configRuleRequest.practiceConfModeTypeCode == 'unify') {
            let legal = checkUnifyPractice(configRuleRequest);
            if (legal == false) {
                return
            }
        } else {
            for (let i = 0; i < configRuleRequest.children.length; i++) {
                let legal = checkUnifyPractice(configRuleRequest.children[i]);
                if (legal == false) {
                    return
                }
            }
        }
        if (configRuleRequest.testConfModeTypeCode == 'unify') {
            let legal = checkUnifytest(configRuleRequest);
            if (legal == false) {
                return
            }
        }
        // 
        let configRuleRequestCopy = JSON.parse(JSON.stringify(configRuleRequest))
        // 测试题库科目检查
        if (configRuleRequestCopy.children && configRuleRequest.testConfModeTypeCode == 'difference') {
            let checkTest = []
            let checkMask = []
            configRuleRequestCopy.children.map((item, index) => {
                if (!item.testAmountConfMap || !item.testPracticePercent || !item.testDurationMinute) {
                    checkTest.push(item)
                }
                for (const key in item.testAmountConfMap) {
                    // 
                    item.testAmountConfMap[key] ? '' : item.testAmountConfMap[key] = 0
                    if (key != 'case') {
                        item.testCorrectConfMap[key].mark ? '' : item.testCorrectConfMap[key].mark = 0
                    }
                    if (key != 'case' && item.testAmountConfMap[key] && item.testCorrectConfMap[key].mark) {
                        if (!checkMask[index]) { checkMask.push(item) }
                    }
                    if (key == 'case' && item.testAmountConfMap[key]) {
                        if (!checkMask[index]) { checkMask.push(item) }
                    }
                }
            })
            if (checkTest[0]) {
                if (!checkTest[0].testPracticePercent) { ElMessage.warning('有科目未输入模拟考试中占练习题库,请检查'); return }
                if (!checkTest[0].testResiduePercent) { ElMessage.warning('有科目未输入模拟考试中全题库剩余题库百分比,请检查'); return }
                if (!checkTest[0].testDurationMinute) { ElMessage.warning('有科目未输入测试用时,请检查'); return }
            }
            if (checkMask.length == 0 || checkMask.length != saveOptions.subOption.length) { ElMessage.warning('有科目未输入题目或分数,请检查'); return }
        }
        const meth = queryReceive.type == 'edit' ? 'PUT' : null
        ruleAddApi(configRuleRequestCopy, meth).then(res => {
            ElMessage.success('操作成功')
            router.replace('/modules/question/rule')
        }).catch((error) => {
            if (error.code == 600) {
                showErrorReason.value = true
                errorReasonList.value = error.rows.map((row) => {
                    row.message = row.message.map((message) => {
                        return { message }
                    })
                    return row
                })
                selectedTabName.value = error.rows[0].bank.courseName
            }
        })
    })
}

// 清除科目遍历数据
const subOptionClear = () => {
    saveOptions.subOption = configRuleObj.subOptionClearSubOption
}
// 清楚
const configRuleRequestClear = (type) => {
    // 编辑和查看不执行
    if (queryReceive.id) { return }
    switch (type) {
        case 'courseParentId': configRuleRequest.courseParentId = ''
            break;
        case 'courseBankTypeId': configRuleRequest.courseBankTypeId = ''
            saveOptions.courseBankTypeOption = ''
            checkRules()
            break;
        default: ''
    }
}
// 类目
const initCourseOption = () => {
    configListApi({ "levelNum": 1 }).then(res => {
        saveOptions.courseOption = res.rows || []
    })
}
//初始化科目指定的列表
const saveOptionsChildrenInit = (subOption) => {
    subOption.map((item, index) => {
        // 添加科目指定排序
        dargList.test[index] = configRuleObj.testDargListInit
        dargList.practice[index] = configRuleObj.practiceDargListInit
        item.children = {
            courseId: item.id,
            courseBankTypeId: configRuleRequest.courseBankTypeId,
            courseName: item.name,
            testPracticePercent: '',
            testResiduePercent: '',
            testDurationMinute: '',
            "testOrderRule": {
                "typeCode": "manualSortType", //排序规则 顺序打乱 disruption 手动排序 manualSortType
                "questionTypeCodeList": [
                    "single",
                    "multiple",
                    "judge",
                    "fillBlank",
                    "shortAnswer",
                    "case"
                ] //题目题型顺序排序
            },
            practiceOrderRule: {
                "typeCode": "manualSortType",
                "questionTypeCodeList": [
                    "single",
                    "multiple",
                    "judge",
                    "fillBlank",
                    "shortAnswer",
                    "case"
                ]
            },
            "testTotalAmount": '',
            "testTotalMark": '',
            "testAmountConfMap": {
                "single": '', //单选题数量
                "judge": '', //判断题数量
                "multiple": '', //多选题数量
                "case": '',//案例题数量
                "fillBlank": '', //填空题数量
                "shortAnswer": '' //简答题数量
            }, //测试题目数量配置,
            testCorrectConfMap: {
                //单选题配置 题目分数
                fillBlank: { mark: '' },
                shortAnswer: { mark: '' },
                single: { mark: '' },
                judge: { mark: '' },
                multiple: {
                    "mark": '', //题目分数
                    "incompleteHalfMarkFlag": true //漏选得一半标签
                }
            }
        }
    })
    // 科目指定回显

    if (configRuleRequest.id && configRuleRequest.children) {
        configRuleRequest.children.map((item, index) => {
            if (subOption[index]) {
                for (let field in item) {
                    if (item[field] == null) {
                        continue;
                    }
                    subOption[index].children[field] = item[field]
                }

                dargList.test[index] = []
                if (subOption[index].children.testOrderRule) {
                    subOption[index].children.testOrderRule.questionTypeCodeList.map((rule) => {
                        let saveLabel = ''
                        switch (rule) {
                            case 'single': saveLabel = '单选'
                                break;
                            case 'multiple': saveLabel = '多选'
                                break;
                            case 'judge': saveLabel = '判断'
                                break;
                            case 'case': saveLabel = '案例'
                                break;
                            case 'fillBlank': saveLabel = '填空'
                                break;
                            case 'shortAnswer': saveLabel = '简答'
                                break;
                            default: ''
                        }
                        dargList.test[index].push({
                            label: saveLabel,
                            value: rule
                        })
                    })

                }

                dargList.practice[index] = []
                if (subOption[index].children.practiceOrderRule) {
                    subOption[index].children.practiceOrderRule.questionTypeCodeList.map((rule) => {
                        let saveLabel = ''
                        switch (rule) {
                            case 'single': saveLabel = '单选'
                                break;
                            case 'multiple': saveLabel = '多选'
                                break;
                            case 'judge': saveLabel = '判断'
                                break;
                            case 'case': saveLabel = '案例'
                                break;
                            case 'fillBlank': saveLabel = '填空'
                                break;
                            case 'shortAnswer': saveLabel = '简答'
                                break;
                            default: ''
                        }
                        dargList.practice[index].push({
                            label: saveLabel,
                            value: rule
                        })
                    })
                }

            }

        })
    }
}
// 科目
const initSubOption = () => {
    configListApi({ "levelNum": 3, "parentId": configRuleRequest.courseParentId, }).then(res => {
        saveOptions.subOption = res.rows || []
        if (saveOptions.subOption.length == 0) { return }

        if (configRuleRequest.testConfModeTypeCode == 'unify' && configRuleRequest.practiceConfModeTypeCode == 'unify' && queryReceive.type != 'add') {
            dargList.test[1] = configRuleObj.testDargListInit
            dargList.practice[1] = configRuleObj.practiceDargListInit
            saveOptions.subOption.map((item, index) => {
                // 添加科目指定排序
                item.children = {
                    courseId: item.id,
                    courseBankTypeId: configRuleRequest.courseBankTypeId,
                    courseName: item.name,
                    testPracticePercent: '',
                    testResiduePercent: '',
                    testDurationMinute: '',
                    "testOrderRule": {
                        "typeCode": "manualSortType", //排序规则 顺序打乱 disruption 手动排序 manualSortType
                        "questionTypeCodeList": [
                            "single",
                            "multiple",
                            "judge",
                            "fillBlank",
                            "shortAnswer",
                            "case"
                        ] //题目题型顺序排序
                    },
                    practiceOrderRule: {
                        "typeCode": "manualSortType",
                        "questionTypeCodeList": [
                            "single",
                            "multiple",
                            "judge",
                            "fillBlank",
                            "shortAnswer",
                            "case"
                        ]
                    },
                    "testTotalAmount": '',
                    "testTotalMark": '',
                    "testAmountConfMap": {
                        "single": '', //单选题数量
                        "judge": '', //判断题数量
                        "multiple": '', //多选题数量
                        "fillBlank": '',
                        "shortAnswer": '',
                        "case": '' //案例题数量
                    }, //测试题目数量配置,
                    testCorrectConfMap: {
                        //单选题配置 题目分数
                        fillBlank: { mark: '' },
                        shortAnswer: { mark: '' },
                        single: { mark: '' },
                        judge: { mark: '' },
                        multiple: {
                            "mark": '', //题目分数
                            "incompleteHalfMarkFlag": true //漏选得一半标签
                        }
                    }
                }
            })
            if (configRuleRequest.id && configRuleRequest.children) {
                configRuleRequest.children.map((item, index) => {
                    if (saveOptions.subOption[index]) {
                        for (let field in item) {
                            if (item[field] == null) {
                                continue;
                            }
                            saveOptions.subOption[index].children[field] = item[field]
                        }


                        if (index == 0) {
                            return;
                        }
                        dargList.test[index] = []
                        if (saveOptions.subOption[index].children.testOrderRule) {
                            saveOptions.subOption[index].children.testOrderRule.questionTypeCodeList.map((rule) => {
                                let saveLabel = ''
                                switch (rule) {
                                    case 'single': saveLabel = '单选'
                                        break;
                                    case 'multiple': saveLabel = '多选'
                                        break;
                                    case 'judge': saveLabel = '判断'
                                        break;
                                    case 'case': saveLabel = '案例'
                                        break;
                                    case 'fillBlank': saveLabel = '填空'
                                        break;
                                    case 'shortAnswer': saveLabel = '简答'
                                        break;
                                    default: ''
                                }
                                dargList.test[index].push({
                                    label: saveLabel,
                                    value: rule
                                })
                            })

                        }

                        dargList.practice[index] = []
                        if (saveOptions.subOption[index].children.practiceOrderRule) {
                            saveOptions.subOption[index].children.practiceOrderRule.questionTypeCodeList.map((rule) => {
                                let saveLabel = ''
                                switch (rule) {
                                    case 'single': saveLabel = '单选'
                                        break;
                                    case 'multiple': saveLabel = '多选'
                                        break;
                                    case 'judge': saveLabel = '判断'
                                        break;
                                    case 'case': saveLabel = '案例'
                                        break;
                                    case 'fillBlank': saveLabel = '填空'
                                        break;
                                    case 'shortAnswer': saveLabel = '简答'
                                        break;
                                    default: ''
                                }
                                dargList.practice[index].push({
                                    label: saveLabel,
                                    value: rule
                                })
                            })
                        }
                    }

                })
            }
        } else {
            saveOptionsChildrenInit(saveOptions.subOption)
        }

        if (configRuleRequest.testConfModeTypeCode != 'unify' || configRuleRequest.practiceConfModeTypeCode != 'unify') {
            saveOptionsChildrenInit(configRuleObj.subOptionClearSubOption)
        }
        // subOptionClear()
    })
}
// 类别
const initCourseOtherOption = () => {
    if (queryReceive.type != 'add') { configRuleRequestClear('courseParentId') }
    configListApi({ "levelNum": 2, "parentId": configRuleRequest.courseIdMain, }).then(res => {
        saveOptions.courseOtherOption = res.rows || []
        if (configRuleRequest.courseParentId) { initCourseBankTypeOption() }
    })
}
// 题库类型
const initCourseBankTypeOption = () => {
    if (queryReceive.type != 'add') {
        configRuleRequestClear('courseBankTypeId');
    }
    initSubOption()
    configBankApi({ courseId: configRuleRequest.courseParentId }).then(res => { saveOptions.courseBankTypeOption = res.rows || [] })
}
// configRuleRequest

//校验表单规则，查看用户是否填写所属类别，题库类型
const clearAllQuestion = () => {
    initSubOption()
    configRuleRequest.id = ''
    configRuleRequest.practicePercent = ''
    configRuleRequest.practiceModeCodeList = []
    configRuleRequest.practiceOrderRule = {
        "typeCode": "manualSortType",
        "questionTypeCodeList": ["single", "multiple", "judge", "case"]
    }
    // dargList.practice[0] = []
    // dargList.test[0] = []
    // setTimeout(() => {
    //     configRuleRequest.practiceOrderRule.questionTypeCodeList.map((rule) => {
    //         let saveLabel = ''
    //         switch (rule) {
    //             case 'single': saveLabel = '单选'
    //                 break;
    //             case 'multiple': saveLabel = '多选'
    //                 break;
    //             case 'judge': saveLabel = '判断'
    //                 break;
    //             case 'case': saveLabel = '案例'
    //                 break;
    //             default: ''
    //         }
    //         dargList.practice[0].push({
    //             label: saveLabel,
    //             value: rule
    //         })
    //     })
    // })
    dargList.test[0] = [...configRuleObj.testDargListInit]
    dargList.practice[0] = [...configRuleObj.practiceDargListInit]
}
async function checkRules(type) {
    if (type == 'courseBankTypeIdCheckRules') {
        ruleByParentAndBankTypeApi({
            "courseParentId": configRuleRequest.courseParentId,
            "courseBankTypeId": configRuleRequest.courseBankTypeId
        }).then((res) => {
            if (res.data == null) {
                clearAllQuestion()
                return
            }
            initSaveConfigRule(res)
        })
    }

    if (configRuleRequest.testConfModeTypeCode == 'unify') {
        showTestDetail.value = true
    } else {
        checkForm(showTestDetail)
    }

    if (configRuleRequest.practiceConfModeTypeCode == 'unify') {
        showPracticeDetail.value = true
    } else {
        checkForm(showPracticeDetail)
    }
}
async function checkForm(showDetail) {
    if (!ruleFormRef.value) {
        showDetail.value = false
        return
    }
    await ruleFormRef.value.validate((valid, fields) => {
        if (!valid) {
            showDetail.value = false
            return
        }
        showDetail.value = true
    })
}

function checkUnifyPractice(rule) {
    if (rule.practicePercent == null) { ElMessage.warning('请选择输入练习题库百分比'); return false }
    if (!rule.practiceModeCodeList || rule.practiceModeCodeList.length == 0) { ElMessage.warning('请选择题库模式'); return false }
    return true;
}

function checkUnifytest(rule) {
    if (rule.testPracticePercent == null) { ElMessage.warning('请选择输入模拟考试中占练习题库'); return false }
    if (rule.testResiduePercent == null) { ElMessage.warning('请输入模拟考试中全题库剩余题库百分比'); return false }
    if (!rule.testDurationMinute) { ElMessage.warning('请选择输入测试用时'); return false }
    let totalTestAmountConfMap = 0
    if (rule.testAmountConfMap) {
        for (const key in rule.testAmountConfMap) {
            rule.testAmountConfMap[key] ? totalTestAmountConfMap += rule.testAmountConfMap[key] : ''
        }
    }
    if (totalTestAmountConfMap == 0) { ElMessage.warning('请选择输入模拟考试题型数量'); return false }
    return true
}

//显示预览题库
function preview() {
    let courseParentName;
    saveOptions.courseOtherOption.forEach((item) => {
        if (item.id == configRuleRequest.courseParentId) {
            courseParentName = item.name
        }
    })

    let courseBankTypeName;
    saveOptions.courseOtherOption.forEach((item) => {
        if (item.id == configRuleRequest.courseBankTypeId) {
            courseBankTypeName = item.name
        }
    })

    //封装预览题库组件需要的参数
    const row = {
        courseParentName,
        courseBankTypeName,
        id: queryReceive.id
    }

    //预览题库
    previewObj.preview(row)
}

</script>
<style lang="scss" scoped>
.configRuleStyle {
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #303133;

    .saveConfig {
        border-top: 1px solid rgba(0, 0, 0, 0.1);
        padding-top: 20px;
    }

    .el-input {
        margin: 0 10px;
    }
}

.catBank {
    cursor: pointer;
}
</style>